package name.marz.to.go.ahg.core.responsehandler;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import name.marz.to.go.ahg.common.util.LogUtil;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;


public class FileResponseHandler implements ResponseHandler<File> {
	private String charset = "UTF-8";
	private static final Logger log = Logger.getLogger(FileResponseHandler.class.getName());
	private File file;
	
	public FileResponseHandler(File file) {
		this.file = file;
	}
	public FileResponseHandler(File file, String charset) {
		this(file);
		this.charset = charset;
	}
	
	@Override
	public File handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		log.info(response.getStatusLine().toString());
		HttpEntity entity = response.getEntity();
		LogUtil.log(Level.FINE, response.getAllHeaders(),"response header");
		// 出力先がディレクトリだった場合、ファイル名の自動生成
		File outFile = null;
		if ( file.isDirectory() ) {
			String filename = "file.txt";
			Header[] rhs = response.getHeaders("Content-Disposition");
			if ( rhs == null || rhs.length == 0) {
				log.warning("header Content-Disposition not found, use default filename:"+filename);
			} else {
				Header h = rhs[0];
				String[] str = h.getValue().split(";");
				for (String s : str) {
					log.fine("h str "+s);
					if ( s.contains("filename") ) {
						filename = s.split("=")[1].replaceAll("\"", "");
						log.fine("out filename found : "+filename);
					}
				}
			}
			outFile = new File(file,filename == null ? "file.txt" : filename );
		} else {
			outFile = file;
		}
		// ファイルに書き込み
		log.info("ファイルに書き込み中 "+outFile.getPath());
		BufferedInputStream in = new BufferedInputStream(entity.getContent());
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
		int buf;
		while ( (buf = in.read()) != -1 ) {
			out.write(buf);
		}
		out.flush();
		out.close();
		EntityUtils.consume(entity);
		log.info("ファイルに書き込み終了");
		return outFile;
	}
	public String getCharset() {
		return charset;
	}
	public void setCharset(String charset) {
		this.charset = charset;
	}
}
